package Client.rpcClient.impl;

import Client.rpcClient.RpcClient;
import common.Message.RpcRequest;
import common.Message.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SimpleSocketRpcClient implements RpcClient {
    private String host;
    private int port;
    public SimpleSocketRpcClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    @Override
    public RpcResponse sendRequest(RpcRequest request) {
        try {
            // 创建Socket对象
            Socket socket = new Socket(host, port);
            // 将对象序列化发送到服务端
            ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
            // 接受并反序列化对象
            ObjectInputStream is = new ObjectInputStream(socket.getInputStream());

            os.writeObject(request);
            os.flush();

            RpcResponse response = (RpcResponse) is.readObject();
            return response;

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
